<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <!-- Bootstrap CSS -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
    <div class="container mt-5">
        <div class="card shadow">
            <div class="card-header bg-primary text-white">
                <h2 class="mb-0">词频统计系统</h2>
            </div>
            
            <div class="card-body">
                <!-- 添加耗时显示区域 -->
                <div class="mb-3 text-muted" id="timeCost">处理耗时: --秒</div>
                
                <form method="post" enctype="multipart/form-data" action="/upload" class="mb-4">
                    <div class="input-group mb-3">
                        <span class="input-group-text">Map线程数</span>
                        <input type="number" name="mapThreads" class="form-control" min="1">
                        <span class="input-group-text">Reduce线程数</span>
                        <input type="number" name="reduceThreads" class="form-control" min="1">
                    </div>
                    <div class="input-group">
                        <input type="file" name="file" class="form-control" accept=".txt">
                        <button type="submit" class="btn btn-primary">提交作业</button>
                    </div>
                </form>

                <!-- 美化结果区域 -->
                <div id="resultArea" class="d-none">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h4 class="text-secondary">统计结果</h4>
                        <div class="input-group w-50 me-3">
                            <span class="input-group-text">搜索</span>
                            <input type="text" id="searchInput" class="form-control" placeholder="输入关键词过滤结果" oninput="filterResults()">
                        </div>
                        <button onclick="exportCSV()" class="btn btn-success">
                            <i class="bi bi-download me-2"></i>导出CSV
                        </button>
                    </div>
                    
                    <!-- 美化表格样式 -->
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr><th>单词</th><th>出现次数</th></tr>
                            </thead>
                            <tbody id="resultTable" class="table-group-divider"></tbody>
                        </table>
                        <!-- 新增分页控件 -->
                        <div class="d-flex justify-content-between align-items-center mt-3">
                            <div class="form-group">
                                <select class="form-select" id="pageSize" onchange="changePageSize()">
                                    <option value="10">每页10条</option>
                                    <option value="20" selected>每页20条</option>
                                    <option value="50">每页50条</option>
                                </select>
                            </div>
                            <nav>
                                <ul class="pagination mb-0" id="pagination"></ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let submitTime; // 记录提交时间
    
        document.querySelector('form').addEventListener('submit', function(e) {
            submitTime = Date.now(); // 记录提交开始时间
            e.preventDefault();
            const formData = new FormData();
            // 修复文件字段获取方式
            const fileInput = this.querySelector('input[type="file"]');
            formData.append('file', fileInput.files[0]);
            
            // 1. 先上传文件获取输入路径
            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(inputPath => {
                // 2. 提交MapReduce作业
                return fetch('/submit', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    // 增加线程数参数传递
                    body: JSON.stringify({ 
                        inputPath: inputPath,
                        mapThreads: document.querySelector('[name="mapThreads"]').value,
                        reduceThreads: document.querySelector('[name="reduceThreads"]').value 
                    })
                });
            })
            .then(response => response.text())
            .then(jobId => {
                // 3. 开始轮询任务状态
                document.getElementById('resultArea').classList.add('d-none'); // 改用classList控制隐藏
                checkStatus(jobId);
            })
            .catch(error => alert('文件处理失败: ' + error));
        });

        // 使用AJAX轮询任务状态
        function checkStatus(jobId) {
            fetch(`/status/${jobId}`)
                .then(response => response.text())
                .then(status => {
                    if (status === 'COMPLETED') {
                        fetchResult(jobId);
                    } else if (status === 'FAILED') {
                        alert('任务处理失败，请检查服务器日志');
                    } else if (status === 'PROCESSING') {
                        setTimeout(() => checkStatus(jobId), 1000);
                    } else {
                        alert('未知的任务状态: ' + status);
                    }
                });
        }

        function updateTimeCost(jobId) {
            fetch(`/time/${jobId}`)
                .then(res => res.json())
                .then(ms => {
                    const sec = (ms / 1000).toFixed(2);
                    document.getElementById('timeCost').textContent = `处理耗时: ${sec}秒 (前端总耗时: ${(Date.now()-submitTime)/1000}秒)`;
                });
        }

        let originalData = []; // 保存原始数据
        
        function fetchResult(jobId) {
            fetch(`/result/${jobId}`)
                .then(response => {
                    if (!response.ok) throw new Error('结果获取失败');
                    return response.json();
                })
                .then(data => {
                    updateTimeCost(jobId);
                    if (!Array.isArray(data)) {
                        console.error('Invalid data format:', data);
                        data = [];
                    }
                    originalData = data.sort((a, b) => b.count - a.count);
                    currentData = [...originalData]; // 初始化当前数据为完整数据集
                    window.currentJobId = jobId;
                    renderTable(currentData);
                    document.getElementById('resultArea').classList.remove('d-none');
                })
                .catch(error => {
                    console.error('Error:', error);
                    const resultArea = document.getElementById('resultArea');
                    resultArea.classList.add('d-none'); // 确保错误时隐藏结果区域
                    alert('结果获取失败: ' + error.message);
                });
        }

        // 新增导出CSV函数
        function exportCSV() {
            if (!window.currentJobId) {
                alert('请先完成数据处理');
                return;
            }
            
            fetch(`/export/${window.currentJobId}`)
                .then(response => {
                    if (!response.ok) throw new Error('导出失败: ' + response.status);
                    return response.blob();
                })
                .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `wordcount_${new Date().toISOString().slice(0,10)}.csv`;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                })
                .catch(error => {
                    console.error('导出错误:', error);
                    alert('导出失败: ' + error.message);
                });
        }

        let currentData = [];
        let currentPage = 1;
        let pageSize = 20;

        function changePageSize() {
            pageSize = parseInt(document.getElementById('pageSize').value);
            currentPage = 1;
            renderTable(currentData);
        }

        function renderTable(data) {
            const start = (currentPage - 1) * pageSize;
            const end = start + pageSize;
            const pageData = data.slice(start, end);
            
            const tbody = document.getElementById('resultTable');
            tbody.innerHTML = pageData.map(item => 
                `<tr><td>${item.word}</td><td>${item.count}</td></tr>`
            ).join('');
            
            renderPagination(data.length);
        }

        function renderPagination(totalItems) {
            const totalPages = Math.ceil(totalItems / pageSize);
            const pagination = document.getElementById('pagination');
            let html = '';
            
            // 添加首页和快速跳转
            html += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(1)">首页</a></li>`;
            html += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a></li>`;

            // 动态页码生成（显示当前页前后2页）
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);
            
            // 前省略号
            if (startPage > 1) {
                html += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(1)">1</a></li>`;
                if (startPage > 2) html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
            
            // 中间页码
            for (let i = startPage; i <= endPage; i++) {
                html += `<li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${i})">${i}</a></li>`;
            }
            
            // 后省略号
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
                html += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${totalPages})">${totalPages}</a></li>`;
            }

            // 添加末页和快速跳转
            html += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a></li>`;
            html += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${totalPages})">末页</a></li>`;
            
            pagination.innerHTML = html;
        }

        function changePage(page) {
            currentPage = page;
            renderTable(currentData);
        }

        // 新增过滤函数
        function filterResults() {
            const keyword = document.getElementById('searchInput').value.toLowerCase();
            currentData = originalData.filter(item => 
                item.word.toLowerCase().includes(keyword)
            );
            currentPage = 1; // 重置到第一页
            renderTable(currentData);
        }
    </script>
</body>
</html>